// +----------------------------------------------------------------------
// | Manong.Cloud [ 领酷码农云 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.manong.cloud All rights reserved.
// +----------------------------------------------------------------------
// | Author: 稻草人 <qinuoyun@qq.com>
// +----------------------------------------------------------------------
// | Member: 围棋 飘逸者 Loumt Silence24
// +----------------------------------------------------------------------
//加载路由
import _router from "koa-router";
//加载URL
import url from "url";
//加载Qs
import qs from "qs";
//执行路由
const router = _router();

//处理API兼容字段
const urlprefix = "/api";

import DataUtil from './../../../utils/DataUtil'

//创建API接口前缀
router.prefix(urlprefix);

//创建执行的API接口
router.all("*", async (ctx, next) => {
  try {
    //查找替换做兼容处理
    let _URL = ctx.url.replace(urlprefix, "/api");
    //处理URL常用常量
    define("$_URL", explode("/", trim(url.parse(_URL, true).path, "/")));

    if(C('security.disable')){
      define("$_POST", ctx.method === "POST" ? ctx.request.body : []);
    }else{
      if(ctx.method === "POST" && ctx.request.body.data){
        const JSON_STRING = DataUtil.RequestRSADecrypt(ctx.request.body.data);
        define("$_POST", JSON.parse(JSON_STRING))
      }else{
        define("$_POST", {})
      }
    }

    define("$_GET", ctx.querystring ? qs.parse(ctx.querystring) : []);
    define("$_FILES", isset(ctx.request.files) ? ctx.request.files : []);
    define("$_METHOD", ctx.method);
    define("$_SERVER", ctx.headers);

    //执行URL参数设置
    let argument = copy_data($_URL);
    let API = argument.shift();
    //判断第一个值是否为空
    API = API ? API : argument.shift();
    let Model = argument.shift();
    let Action = argument.shift().split("?").shift();
    //处理获取自动化模型
    let Automate, CloudName = "";

    if (argument.length >= 2) {
      Automate = argument.shift().split("?").shift();
      CloudName = argument.shift().split("?").shift();
      define("$_AUTOCODE", {
        model: Automate,
        action: CloudName
      });
    }


    //获取对应的API数据文件
    const instance = getApiFile(Model);
    //判断是否函数
    if (typeof instance == "function") {
      try {
        const target = new instance(ctx, next);
        //设置执行方法名称,名称需要转驼峰命名方式
        const defaultAction = "action" + ucfirst(to_hump(Action));
        //执行代理方法
        let handlers = {
          get(target, property) {
            //判断方法是否存在，如果不存在的情况下设置方法
            if (typeof (target[property]) === "function") {
              return target[property].apply(target);
            } else {
              //判断模型下是否存在_call方法，如果存在就调用，不存在就报错
              if (typeof (target.__call) === "function") {
                return target.__call.apply(target, [property, ctx]);
              } else {
                throw new Error(`[${Model}]控制器下，方法[${property}]不存在`);
              }
            }
          }
        };
        //执行该对象方法且处理异步方法
        const proxy = new Proxy(target, handlers);

        let response = await proxy[defaultAction]

        if(C('security.disable')){
          ctx.body = {
            code: 0,
            msg: "succeed",
            data: response
          };
        }else{
          ctx.body = {
            code: 0,
            msg: "succeed",
            data: DataUtil.ResponseRSAEncrypt(JSON.stringify(response))
          };
        }
      } catch (error) {
        throw error;
      }
    } else {
      throw new Error("API文件" + api_file + "非类文件或无module.exports输出");
    }
  } catch (error) {
    throw error;
  }
});

/**
 * 获取API文件
 * @return {[type]} [description]
 */
const getApiFile = function(Name) {
  const controller = "controllers/" + ucfirst(Name) + "Controller";
  return getComponent(controller);
};

export default router;
